package cn.tedu.ivos.dictoption.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictoptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictoptionQuery;
import cn.tedu.ivos.dictoption.pojo.dto.DictoptionSaveParam;
import cn.tedu.ivos.dictoption.pojo.entity.Dictoption;
import cn.tedu.ivos.dictoption.pojo.vo.DictoptionVO;
import cn.tedu.ivos.dictoption.service.DictoptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictoptionServiceImpl implements DictoptionService {

    @Autowired
    DictoptionMapper dictoptionMapper;
    @Autowired
    private DictMapper dictMapper;


    @Override
    public List<DictoptionVO> selectDictoption(DictoptionQuery query) {
        log.debug("查询字典项："+query);
        List<DictoptionVO> list = dictoptionMapper.selectDictoption(query);
        return list;
    }

    @Override
    public void saveDictoption(DictoptionSaveParam param) {
        log.debug("添加字典业务参数：{}", param);
        Dictoption dictoption = new Dictoption();
        BeanUtils.copyProperties(param,dictoption);
        if (dictoption.getId()==null){
            dictoption.setCreateTime(new Date());
            dictoptionMapper.saveDictoption(dictoption);
        }else {
            dictoption.setUpdateTime(new Date());
            dictoptionMapper.updateDictoption(dictoption);
        }
    }

    @Override
    public void deleteDictoption(Long id) {
        log.debug("删除字典项：id="+id);
        dictoptionMapper.deleteDictoption(id);
    }

    @Override
    public List<DictoptionVO> selectCode(String code) {
    log.debug("查询字典项：code="+code);
        DictQuery query = new DictQuery();//封装字典查询对象
        query.setCode(code);//设置字典编码
        List<DictVO>dictVOlist = dictMapper.selectDict(query);//根据查询对象查字典
        if (dictVOlist!=null && dictVOlist.size()>0){//如果查询到值
            DictVO dictVO = dictVOlist.get(0);//获取字典对象
            DictoptionQuery dictoptionQuery = new DictoptionQuery();//封装字典查询对象
            dictoptionQuery.setDictId(dictVO.getId());//设置字典ID
            List<DictoptionVO> dictoptionVOlist=
                    dictoptionMapper.selectDictoption(dictoptionQuery);//根据查询对象查字典项
            return dictoptionVOlist;//返回数据给字典列表
        }else {
            throw new ServiceException(StatusCode.DATA_UNEXISTS);//数据不存在
        }


    }
}
